import { defineStore } from 'pinia'
import { Ref, ref } from "vue";
import Cookies from 'js-cookie';
export const useStore = defineStore('user', () => {
  // 用户令牌
  const token: Ref<string> = ref('');
  // 用户id
  const uid: Ref<string> = ref('');
  // 用户名
  const userinfo: Ref<any> = ref({});
  //是否超级管理员
  const isSuperAdmin: Ref<boolean> = ref(false);
  //渠道id
  const channel_id:Ref<any> = ref(0);
  //城市id
  const city_id:Ref<string> = ref('');
  //城区id
  const area_id:Ref<string> = ref('');
  //街道id
  const street_id:Ref<string> = ref('');
  //类型
  const type: Ref<any> = ref({});
  //渠道类型
  const channel_level = ref(0);
  interface loginInfoStorageInterface {
    token: string,
    uid: string,
    userinfo: any,
    isSuperAdmin: boolean,
    channel_id:number,
    city_id:string,
    area_id:string,
    street_id:string,
    type:any,
  }
  // 登录
  const login = (loginInfo: loginInfoStorageInterface) => {
    token.value = loginInfo.token || '';
    uid.value = loginInfo.uid || '';
    userinfo.value = loginInfo.userinfo || {};
    isSuperAdmin.value = loginInfo.isSuperAdmin || false;
    channel_id.value = loginInfo.channel_id || 0;
    city_id.value = loginInfo.city_id || '';
    area_id.value = loginInfo.area_id || '';
    street_id.value = loginInfo.street_id || '';
    type.value = loginInfo.type || '';
        if(city_id.value != '' && area_id.value == '' && street_id.value == '')
          {
             channel_level.value = 1;
          }
          else if (city_id.value != '' && area_id.value != '' && street_id.value == '')
          {
            channel_level.value = 2;
          }
          else if (city_id.value != '' && area_id.value != '' && street_id.value != '')
          {
            channel_level.value = 3;
          }
  }
  const logout = () => {
    token.value = '';
    uid.value = '';
    channel_id.value = '';
    city_id.value ='';
    area_id.value = '';
    street_id.value='';
    type.value ='';
    userinfo.value = {};
    channel_level.value = 0;
  }
  return {
    token,
    uid,
    isSuperAdmin,
    userinfo,
    channel_id,
    city_id,
    area_id,
    street_id,
    channel_level,
    type,
    login,
    logout,
  }
}, {
  persist: {
    enabled: true,
    strategies: [{
      key: process.env.VUE_APP_ENV + "user",
      storage: {
        getItem: (key: string) => Cookies.get(key),
        setItem: (key: string, val: any) => Cookies.set(key, val),
        removeItem: (key: string) => Cookies.remove(key),
      },
    }]
  }
} as any)
